import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';
import printJS from 'print-js';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Input,
  Row,
  Select,
  DatePicker,
  message,
  Modal,
} from 'antd';

import '@ant-design/compatible/assets/index.css';
import Pagination from '../../components/Pagination';
import PrintElemInfo from './components/PrintElem';

const orderStatus = {
  1: '已接驳',
  2: '已取走',
  3: '已退回',
  4: '在库',
};

const { Item } = Form;
const { Option } = Select;
const { RangePicker } = DatePicker;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  logisCenterBatchDetail: any;
  INITINFO: any;
  location: any;
  loading: boolean;
  screen: string;
}

interface TableListState {
  current: number;
  pageSize: number | undefined;
  formValues: any;
  batchIds: any;
  modifyPhoneDialog: boolean;
  phone: string;
  orderInfo: any;
  rowId:number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
  logisCenterBatchDetail,
  common: { INITINFO },
  global: { screen },
  loading,
}: any) => ({
  logisCenterBatchDetail,
  INITINFO,
  screen,
  loading: loading.effects['logisCenterBatchDetail/fetch'],
}))

class TableList extends React.Component<TableListProps, TableListState> {
  columns: any = [
    {
      title: '运单号',
      dataIndex: 'expCode',
      width: 150,
      render: (text: any) => (
        <div title={text} className="wordOmit">
          {text}
        </div>
      ),
    },
    {
      title: '外部商品订单号',
      dataIndex: 'outOrderId',
      width: 150,
      render: (text: string) => text || '--',
    },
    {
      title: '到付金额',
      dataIndex: 'payment',
      width: 100,
      render: (text: number) => `${(text / 100).toFixed(2)} 元`,
    },
    {
      title: '收件人手机',
      dataIndex: 'consigneePhone',
      width: 120,
      render: (text: string) => text || '--',
    },
    {
      title: '接驳人/手机号',
      dataIndex: 'transhipUser',
      width: 160,
      render: (text: string, record: any) => `${text} / ${record.transhipPhone}`,
    },
    {
      title: '接驳时间',
      dataIndex: 'createTime',
      width: 150,
      render: (text: string) => text || '--',
    },
    {
      title: '取走时间',
      dataIndex: 'outTime',
      width: 150,
      render: (text: string) => text || '--',
    },
    {
      title: '状态',
      dataIndex: 'statusName',
      width: 100,
    },
    {
      title: '操作',
      fixed: 'right',
      width: 120,
      render: (text: any, record: any) => (
        <span
          className="operLink"
          onClick={() => this.handleOpenModifyPhone(record)}
        >
          修改手机号
        </span>
      ),
    },
  ];

  state: TableListState = {
    current: 1,
    pageSize: 10,
    formValues: {},
    batchIds: [],
    modifyPhoneDialog: false,
    phone: '',
    orderInfo: {},
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 10),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchBatchCommon();
    this.fetchBatchDetail();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchBatchDetail();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const {
      formValues: {
        id, startTime, endTime, maxId, minId, ...others
      },
    } = this.state;

    if (startTime) {
      others.start_end_time = [moment(startTime), moment(endTime)];
    } else {
      others.start_end_time = '';
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  };

  // 获取基本数据
  fetchBatchCommon = () => {
    const {
      dispatch, location: { query: { id: batchId } },
    } = this.props;
    dispatch({
      type: 'logisCenterBatchDetail/fetchCommon',
      payload: { batchId },
    });
  };

  // 获取列表数据
  fetchBatchDetail = () => {
    const {
      location: { query },
      logisCenterBatchDetail: { data },
    } = this.props;

    const { maxId, minId, ...other } = query;
    const search = qs.stringify(other);
    const { current } = this.state;
    const contentObj = data.content.find((item: any) => item.current === current);

    if (contentObj && search === contentObj.search) {
      this.setState({});
    } else {
      const { dispatch } = this.props;
      dispatch({
        type: 'logisCenterBatchDetail/fetch',
        payload: {
          params: this.getQueryParams(),
          search,
          maxId,
          minId,
        },
      });
    }
  };

  // 获取查询参数
  getQueryParams = () => {
    const { formValues, current: pageIndex, pageSize } = this.state;
    const {
      location: { query: { id: batchId } },
    } = this.props;

    const params = {
      ...formValues,
      pageIndex,
      pageSize,
      batchId,
    };

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const {
      form: { validateFields },
      location: { query: { id } },
    } = this.props;

    validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.start_end_time && fieldsValue.start_end_time.length) {
        fieldsValue.startTime = moment(fieldsValue.start_end_time[0]).format('YYYY-MM-DD HH:mm:ss');
        fieldsValue.endTime = moment(fieldsValue.start_end_time[1]).format('YYYY-MM-DD HH:mm:ss');
      } else {
        fieldsValue.startTime = '';
        fieldsValue.endTime = '';
      }
      delete fieldsValue.start_end_time;

      const query = { id, page: 1, ...fieldsValue };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: `查看${id}`,
        url: `/logisCenter/batch/list/detail?${qs.stringify(query)}`,
        isTopMenu: true,
      });
      dispatch({ type: 'logisCenterBatchDetail/cleanCount' });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch, location: { query: { id } } } = this.props;
    addTab(dispatch, {
      name: `查看${id}`,
      url: `/logisCenter/batch/list/detail?id=${id}`,
      isTopMenu: true,
    });
    dispatch({ type: 'logisCenterBatchDetail/cleanCount' });
  };

  /**
   * 打开修改手机号弹窗
   */
  handleOpenModifyPhone = (orderInfo: any) => {
    const { dispatch }: any = this.props;
    dispatch({
      type: 'logisCenterBatchDetail/checkModify',
      payload: { orderId: orderInfo.id },
    }).then((result: any) => {
      if (result.body) {
        this.setState({
          orderInfo,
          modifyPhoneDialog: true,
        });
      } else {
        message.error('该接驳运单已经投递或移库,无法修改!');
      }
    });
  };

  /**
   * 关闭修改手机号弹窗
   */
  handleCloseModifyPhone = () => this.setState({ modifyPhoneDialog: false, phone: '' });

  /**
   * 修改手机号
   */
  handleModifyPhone = () => {
    const { phone } = this.state;
    if (!phone.trim()) {
      message.error('手机号不能为空');
      return;
    }

    const { dispatch } = this.props;
    const { orderInfo: { id: orderId } } = this.state;
    dispatch({
      type: 'logisCenterBatchDetail/modify',
      payload: {
        params: { orderId, phone },
        query: this.getQueryParams(),
      },
    });
    this.handleCloseModifyPhone();
  };

  /**
   * 批量删除
   */
  handleBatchDelete = () => {
    const { batchIds } = this.state;
    if (!batchIds.length) {
      message.error('请选择需要删除的数据！');
      return;
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterBatchDetail/delete',
      payload: {
        query: this.getQueryParams(),
        params: { idList: batchIds.toString() },
      },
    });
  };

  /**
   * 打印运单条形码
   */
  handlePrintCode = () => {
    printJS({
      printable: 'billDetails',
      type: 'html',
      targetStyles: ['*'],
      onPrintDialogClose: () => '关闭',
      onError: error => error,
    });
  };

  /**
   * 下载运单条形码
   */
  handleDownloadCode = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterBatchDetail/download',
      payload: this.getQueryParams(),
    });
  };

  /**
   * 输入新手机号
   */
  handleChangePhone = (e: any) => this.setState({ phone: e.target.value });

  /**
   * 查看总数
   */
  handleShowCount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterBatchDetail/count',
      payload: this.getQueryParams(),
    });
  };

  // 选择列表项
  onChangeItem = (batchIds: any) => this.setState({ batchIds });

  // 分页
  onSelectChange = (type: string) => {
    const { formValues, current, pageSize: psize } = this.state;
    const {
      location: { query: { id } },
      logisCenterBatchDetail: { data },
    } = this.props;

    const query = {
      ...formValues,
      page: type === 'prev' ? current - 1 : current + 1,
      psize,
    };

    const contentObj = data.content.find((item: any) => item.current === current);
    if (type === 'prev') {
      if (contentObj?.list?.length) {
        query.minId = contentObj.list[0].id;
      } else {
        query.minId = contentObj.maxId || contentObj.minId;
      }
      delete query.maxId;
    } else if (type === 'next') {
      const list = contentObj ? contentObj.list : [];
      query.maxId = list[list.length - 1].id;
      delete query.minId;
    }

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${id}`,
      url: `/logisCenter/batch/list/detail?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  // 选择显示行数
  onShowSizeChange = (pageSize: number) => {
    const { formValues } = this.state;
    const query = { ...formValues, page: 1, psize: pageSize };
    const { dispatch, location: { query: { id } } } = this.props;
    addTab(dispatch, {
      name: `查看${id}`,
      url: `/logisCenter/batch/list/detail?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem = () => {
    const {
      form: { getFieldDecorator },
      logisCenterBatchDetail: { common },
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Item label="　　快递公司" colon={false}>{common.expressName}</Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="　物流中心" colon={false}>{common.logisName}</Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="　　批次" colon={false}>第 {common.seqNo} 批</Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="批次日期" colon={false}>{common.batchDate}</Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={12} sm={24}>
            <Item label="　取走时间" colon={false}>
              {getFieldDecorator('start_end_time')(
                <RangePicker
                  showTime
                  placeholder={['开始时间', '截止时间']}
                  style={{ width: '100%' }}
                  format="YYYY/MM/DD HH:mm:ss"
                  disabledDate={timeLimit}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="是否到付" colon={false}>
              {getFieldDecorator('isPayment')(
                <Select
                  allowClear
                  placeholder="请选择"
                  style={{ width: '100%' }}
                >
                  <Option value="1">是</Option>
                  <Option value="2">否</Option>
                </Select>,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Item label="接驳人手机" colon={false}>
              {getFieldDecorator('transhipPhone')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="收件人手机" colon={false}>
              {getFieldDecorator('consigneePhone')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="快递状态" colon={false}>
              {getFieldDecorator('orderStatus')(
                <Select
                  allowClear
                  placeholder="请选择"
                  style={{ width: '100%' }}
                >
                  {Object.keys(orderStatus).map(key => (
                    <Option key={String(key)} value={String(key)}>
                      {orderStatus[key]}
                    </Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Item label="　　运单号" colon={false}>
              {getFieldDecorator('expCode')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="是否代签收" colon={false}>
              {getFieldDecorator('isSigned')(
                <Select allowClear placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="1">是</Option>
                  <Option value="0">否</Option>
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  // 渲染修改手机号弹窗
  renderModifyPhoneModalElem = () => {
    const { modifyPhoneDialog, phone, orderInfo } = this.state;
    const { logisCenterBatchDetail: { common } } = this.props;

    return (
      <Modal
        title="修改手机号"
        visible={modifyPhoneDialog}
        onOk={this.handleModifyPhone}
        onCancel={this.handleCloseModifyPhone}
      >
        <Form className="tableListForm">
          <Row>
            <Col md={20} sm={20}>
              <Item label="　快递单号" colon={false}>
                <Input allowClear disabled value={orderInfo.expCode} />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Item label="　快递公司" colon={false}>
                <Input allowClear disabled value={orderInfo.expressName} />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Item label="　快递批次" colon={false}>
                <Input allowClear disabled value={common.seqNo} />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Item label="收件人手机" colon={false}>
                <Input
                  allowClear
                  type="number"
                  placeholder="请输入"
                  value={phone}
                  onChange={this.handleChangePhone}
                />
              </Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  };

  render() {
    const { current, pageSize, batchIds: selectedRowKeys } = this.state;
    const {
      logisCenterBatchDetail: { data, common },
      loading,
      screen,
    } = this.props;

    const rowSelection = { selectedRowKeys, onChange: this.onChangeItem };
    const contentObj = data.content.find((item: any) => item.current === current);
    const list = (contentObj ? contentObj.list : []) || [];

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleBatchDelete}
            >
              批量删除
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handlePrintCode}
            >
              打印运单条形码
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleDownloadCode}
            >
              下载运单条形码
            </Button>
          </div>
          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            rowSelection={rowSelection}
            columns={this.columns}
            dataSource={list}
            pagination={false}
            loading={loading}
            scroll={{ x: 1500 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
          {(current > 1 || list.length > 0) && (
            <Pagination
              current={current}
              pageSize={pageSize}
              total={data.count}
              length={list.length}
              showCount={this.handleShowCount}
              onChange={this.onSelectChange}
              onShowSizeChange={this.onShowSizeChange}
            />
          )}
        </Card>

        {this.renderModifyPhoneModalElem()}

        <PrintElemInfo dataList={list} common={common} />
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
